﻿@model Mindfor.Web.Data.Page
@{
	// page and edit data
	bool isEdit = Model != null;
	PageEditModel data = ViewBag.Data;
	int? pageId = !isEdit ? (int?)null : Model.Id;
	bool isAdmin = ViewBag.IsAdmin;
	
	PageTitle.AddViewTitle("Страницы", Url.Action("Index"));
	if (Model == null)
	{
		PageTitle.AddViewTitle("Добавление");
	}
	else
	{
		PageTitle.AddViewTitle(Model.Name);
		PageTitle.AddViewTitle("Изменение");
	}	
	
	// parents
	List<SelectListItem> parentsList = data.Pages.GetTreePages(Model)
		.Where(r => !String.IsNullOrEmpty(r.Name) || r.Parent != null)
		.Select(r => new SelectListItem
			{
				Text = "/" + r.GetPath() + "/",
				Value = r.Id.ToString()
			})
		.ToList();
	parentsList.Insert(0, new SelectListItem() { Text = "/", Value = "" });
	//int? selectedId = ViewData.Eval<int?>("ParentId");

	// tags
	string tagsStr = "";
	IEnumerable<Tag> tags = ViewData.Eval<IEnumerable<Tag>>("Tags");
	if (tags != null)
	{
		tagsStr = tags.Select(t => t.Name).Merge(", ");
	}
	
	// actions lists
	Dictionary<string, string> actionsDic = new Dictionary<string, string>();
	List<SelectListItem> modulesList = new List<SelectListItem>();
	modulesList.Add(new SelectListItem { Text = "Текстовая страница", Value = "" });

	foreach (var group in data.Actions.GroupBy(r => r.ModuleName))
	{
		modulesList.Add(new SelectListItem() { Text = group.Key });
		actionsDic.Add(group.Key, group.Select(r => r.ControllerName + " / " + r.ActionName).Merge(","));
	}
	
	string actionsDicJson = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(actionsDic);
		
	string selectedModule = ViewData.Eval<string>("ActionPath.ModuleName");
	IEnumerable<SelectListItem> controllerAndActionsList = data.Actions
		.Where(r => r.ModuleName == selectedModule)
		.Select(r => new SelectListItem
		{
			Text = r.ControllerName + " / " + r.ActionName
		}
	);

	// roles data
	PageEditRolesData rolesData = new PageEditRolesData()
	{
		Roles = data.Roles,
		SelectedAnonymous = ViewData.Eval<bool>("AllowAnonymous", true),
		SelectedAuthorized = ViewData.Eval<bool>("AllowAuthorized", true),
		SelectedRoles = Model == null ? null : Model.AllowRoles.Select(r => r.Name)
	};

	// pageTexts
	IList<PageText> pageTexts = ViewData.Eval<IList<PageText>>("Texts");
	if (pageTexts == null)
	{
		pageTexts = new List<PageText>();
	}
	
	List<Language> addLangs = new List<Language>();
	foreach (Language lang in data.Languages)
	{
		if (!pageTexts.Any(pt => pt.Language == lang))
		{
			addLangs.Add(lang);
		}
	}
	int selectedLanguageId = ViewData.Eval<int>("LanguageId");
}

@section head {
	@Html.Partial("Mce", new MceModel(true, data.MceFolder))

	<style type="text/css">
		.auth
		{
			margin-left: 20px;
		}
		
		.role
		{
			margin-left: 40px;
		}
		
		ul.langs li.add a:before
		{
			content: 'Добавить ';
		}
		
		.pageTextEditor
		{
			clear: both;
			margin: 0px;
			overflow: auto;
		}
	</style>

	<script type="text/javascript">
		var moduleActions = @(actionsDicJson.AsHtml())

		$(document).ready(function() {
			$("#ActionPath_ModuleName").change(function() {
				var m = $(this).val();
				var c = "";
				var a = "";
				var actions = moduleActions[m];
				var actionsDropDown = $("#ControllerAndAction").empty();
				if (actions) {
					var actionItems = actions.split(",");
					for (var i=0; i<actionItems.length; i++)
					{
						actionsDropDown.append("<option value='" + actionItems[i] + "'>" + actionItems[i] + "</option>");
						if (i == 0)
						{
							var ca = actionItems[i].split(" / ");
							c = ca[0];
							a = ca[1];
						}
					}
					actionsDropDown.trigger("liszt:updated");
				}

				reloadRoles(m, c, a);
			});

			$("#ControllerAndAction").change(function () {
				var m = $("#ActionPath_ModuleName").val();
				var ca = $(this).val().split(" / ");
				if (ca.length == 2)
					reloadRoles(m, ca[0], ca[1]);
			});

			$("#AllowAuthorized").live("click", function() {
				if ($(this).prop("checked")) {
					$("label.auth").show("normal");
					$("label.role").show("normal");
				}
				else {
					$("label.auth").hide("normal").eq(0).find("input").prop("checked", true);
					$("label.role").hide("normal").find("input").prop("disabled", true).prop("checked", false);
				}
			});

			$("#AuthRoles, #AuthAll").live("click", function() {
				if ($("#AuthRoles").prop("checked"))
					$("label.role input").prop("disabled", false);
				else
					$("label.role input").prop("disabled", true).prop("checked", false);
			});

			$("ul.langs a").click(function() {
				var t = $(this);
				$("ul.langs li").removeClass("selected");
				var langId = t.parents("li").eq(0)
					.addClass("selected")
					.removeClass("add")
					.data("language-id");

				$("div.pageText").hide();
				$("#PageText-" + langId).show()
					.find(".isEmpty").val(false);
			});

			$("div.pageText a.delete").click(function () {
				var t = $(this);
				var pageText = t.parents(".pageText").eq(0).hide();
				pageText.find(".isEmpty").val(true).hide();

				var langId = pageText.find(".languageId").val();
				var tab = $("#PageTextTab-" + langId).removeClass("selected").addClass("add");
			});

			$(".headTitleEmpty").change(function () {
				var t = $(this);
				var headTitleId = t.prop("id").substring(0, t.prop("id").indexOf("Empty"));
				var headTitle = $("#" + headTitleId);
				if (t.prop("checked"))
					headTitle.prop("disabled", true);
				else
					headTitle.removeProp("disabled");
			});

			$("input.editorRadio").live("change", function() {
				var t = $(this);
				var pageText = t.parents(".pageText").eq(0);
				var textArea = pageText.find("textarea.editor");
				var editorClass = pageText.find("input.editorRadio:checked").data("editor-class");
				
				removeMce();
				textArea.prop("class", "editor "+editorClass);
				initMce();
			});			
		});

		function reloadRoles(module, controller, action) {
			var fieldset = $("#RolesFieldset");
			var url = '@Url.Action("EditRoles")';
			fieldset.block();
			$.get(url, { id: "@pageId", moduleName:module, controllerName:controller, actionName:action, rand:Math.random() }, function(data) {
				fieldset.unblock();
				fieldset.children(":not(legend)").remove();
				fieldset.append(data);
			});
		}
	</script>
}

@using (Html.BeginForm(null, null, FormMethod.Post, new { id="PageForm", enctype="multipart/form-data" }))
{
	@Html.Hidden("ReturnUrl");
	@Html.ValidationSummary()
		
	<div class="form-buttons">
		<input type="submit" value="@(isEdit ? "Изменить" : "Создать")" />&nbsp;
		<a href="@ViewBag.ReturnUrl">Отменить</a>
	</div>
		
	<fieldset class="form-horizontal">
		<legend>Основные настройки</legend>
		<div>
			@Html.LabelFor(m => m.Name)
			<div>
				@Html.DropDownListFor(m => m.Parent.Id, parentsList, new { style="display:inline-block; width:200px;" })
				@Html.TextBoxFor(m => m.Name, new { style="display:inline-block; width:200px;" })
				<div class="hint">Путь может содержать только символы латинского алфавита, цифры, символы тире и подчеркивания.</div>
			</div>
		</div>
		<div>
			@Html.LabelFor(m => m.Tags)
			<div>
				@Html.TextArea("Tags", tagsStr, new { rows=3 })
				<div class="hint">Теги содержат информацию для поисковых систем. Они не отображаются пользователю</div>
			</div>
		</div>
		<div>
			@Html.LabelFor(m => m.Image)
			@Html.ImageUpload("Image", "imageType")
		</div>
		<label for="ShowInMenu" class="checkbox">
			@Html.CheckBoxFor(m => m.ShowInMenu)
			@Html.DisplayNameFor(m => m.ShowInMenu)
			<div class="hint">Будет отображаться только если задан <b>заголовок</b> или <b>текст меню</b> на выбранном языке</div>
		</label>
		<label for="OpenInNewWindow" class="checkbox">
			@Html.CheckBoxFor(m => m.OpenInNewWindow)
			@Html.DisplayNameFor(m => m.OpenInNewWindow)
		</label>
	</fieldset>
	if (isAdmin) {
	<fieldset class="form-horizontal">
		<legend>Настройки модуля</legend>
		<div>
			@Html.LabelFor(m => m.ActionPath.ModuleName)
			@Html.DropDownListFor(m => m.ActionPath.ModuleName, modulesList)
		</div>
		<div>
			<label for="ControllerAndAction">@Html.DisplayNameFor(m => m.ActionPath.ControllerName) / @Html.DisplayNameFor(m => m.ActionPath.ActionName)</label>
			@Html.DropDownList("ControllerAndAction", controllerAndActionsList)
		</div>
	</fieldset>
	}
	<fieldset id="RolesFieldset" class="form-horizontal">
		<legend>Настройки доступа</legend>
		@Html.Partial("EditRoles", rolesData)
	</fieldset>

	<fieldset id="PageTextFieldset" class="tabs">
		<legend>Текст страницы</legend>
		@if (data.Languages.Count > 1)
		{
			<ul class="langs">
				@foreach (PageText pt in pageTexts) {
					<li id="PageTextTab-@pt.Language.Id" @(selectedLanguageId == pt.Language.Id ? " class='selected'".AsHtml() : null) data-language-id="@pt.Language.Id">
						<a href="#PageText-@pt.Language.Id">@pt.Language.Name</a>
					</li>
				}
				@foreach (Language l in addLangs) {
					<li id="PageTextTab-@l.Id" class="@(selectedLanguageId == l.Id ? "selected" : "add")" data-language-id="@l.Id">
						<a href="#PageText-@l.Id">@l.Name</a>
					</li>
				}
			</ul>
		}
		@{ int pageTextIndex = 0; }
		@foreach (PageText pt in pageTexts)
		{
			string prefix = "Texts[" + pageTextIndex++ + "]";
			<div id="PageText-@pt.Language.Id" class="pageText @(selectedLanguageId == pt.Language.Id ? "" : " hidden")">
				@Html.Partial("EditText", pt, prefix)
			</div>
		}
		@foreach (Language l in addLangs) {
			PageText pt = new PageText();
			pt.Language = l;
			if (selectedLanguageId != l.Id)
			{
				ViewData["Texts[" + pageTextIndex + "].IsDeleted"] = true;
			}
			string prefix = "Texts[" + pageTextIndex++ + "]";
			<div id="PageText-@l.Id" class="pageText @(selectedLanguageId == l.Id ? "" : " hidden")">
				@Html.Partial("EditText", pt, prefix)
			</div>
		}
	</fieldset>
		
	<div class="form-buttons">
		<input type="submit" value="@(isEdit ? "Изменить" : "Создать")" />&nbsp;
		<a href="@ViewBag.ReturnUrl">Отменить</a>
	</div>
}